package com.xls.box2023.login;

import android.app.Activity;
import android.text.TextUtils;

import com.lzz.bottomencapsulation.BuildConfig;
import com.lzz.bottomencapsulation.manager.RiskManager;
import com.lzz.bottomencapsulation.net.RequestCallBack;
import com.lzz.bottomencapsulation.net.RetrofitBase;
import com.lzz.bottomencapsulation.utils.AppUtils;
import com.lzz.bottomencapsulation.utils.LUtils;
import com.lzz.bottomencapsulation.utils.SPUtils;
import com.lzz.bottomencapsulation.utils.TUtils;
import com.xls.box2023.BoxAppLication;
import com.xls.box2023.entity.UserEntity;
import com.xls.box2023.entity.WXEntity;
import com.xls.box2023.entity.WXUserInfoEntity;
import com.xls.box2023.home.HomeActivity;
import com.xls.box2023.network.CallbackT;
import com.xls.box2023.network.RequestManager;
import com.xls.box2023.network.RequestManager2;
import com.xls.box2023.network.RequestManager3;
import com.xls.box2023.network.Transformer;
import com.xls.box2023.utils.AESUtil;
import com.xls.box2023.utils.CallbackInt;
import com.xls.box2023.utils.ChannelUtils;
import com.xls.box2023.utils.SysDataUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


public class LoginNetworkUtil {
    static LoginNetworkUtil loginNetworkUtil=null;
    public static LoginNetworkUtil getInstance() {
        if (loginNetworkUtil==null){
            loginNetworkUtil=new LoginNetworkUtil();
        }
        return loginNetworkUtil;
    }

    public void getAccessToken(Activity activity,String code,Map<String, String> stringStringMap){

        RequestManager2.getInstance(BoxAppLication.getBaseApplication()).
                getAccessToken(BuildConfig.WX_APP_ID,BuildConfig.WX_SECRET,code,"authorization_code")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Observer<WXEntity>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull WXEntity wxEntity) {
                        if (!TextUtils.isEmpty(wxEntity.getAccess_token())) {
                            getWXUserInfo(activity,wxEntity.getAccess_token(),wxEntity.getOpenid(),stringStringMap);
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (LoginActivity.loginActivity!=null){
                            LoginActivity.loginActivity.dissmiss();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });

//    Observable<WXEntity> observable=  RequestManager2.getInstance(BoxAppLication.getBaseApplication()).
//                getAccessToken("wx4d755d8d1e898f6f","ed8922780c9664ffa44f7b496b6ee3f4",code,"authorization_code");
//        observable.subscribeOn(Schedulers.io())               // （初始被观察者）切换到IO线程进行网络请求1
//                .observeOn(AndroidSchedulers.mainThread())  // （新观察者）切换到主线程 处理网络请求1的结果
//                .doOnNext(new Action1<WXEntity>() {
//                    @Override
//                    public void call(WXEntity wxEntity) {
//                        if (TextUtils.isEmpty(wxEntity.getAccess_token())) {
//                            LUtils.e("getAccessToken--失败");
//                        }
//                    }
//                })
//                .doOnError(new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//                        LUtils.e("getAccessToken--失败");
//                    }
//                })
//                .observeOn(Schedulers.io())
//                .flatMap(new Func1<WXEntity, Observable<WXUserInfoEntity>>() {
//                    @Override
//                    public Observable<WXUserInfoEntity> call(WXEntity wxEntity) {
//                        if (!TextUtils.isEmpty(wxEntity.getAccess_token())) {
//                            return RequestManager3.getInstance(BoxAppLication.getBaseApplication()).
//                                    getWXUserInfo(wxEntity.getAccess_token(), wxEntity.getOpenid(), "zh_CN ");
//                        } else {
//                            return null;
//                        }
//
//                    }
//                }
//                ).flatMap(new Func1<WXUserInfoEntity, Observable<HttpRequest<String>>>() {
//                    @Override
//                    public Observable<HttpRequest<String>> call(WXUserInfoEntity wxUserInfoEntity) {
//                        if (!TextUtils.isEmpty(wxUserInfoEntity.getUnionid())){
//                            return RequestManager.getInstance(BoxAppLication.getBaseApplication()).
//                                    getLogin(wxUserInfoEntity.getOpenid(),wxUserInfoEntity.getNickname(),wxUserInfoEntity.getHeadimgurl(),wxUserInfoEntity.getUnionid());
//                        }
//                        return null;
//                    }
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<HttpRequest<String>>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        LUtils.e("登陆失败"+e.toString());
//                    }
//
//                    @Override
//                    public void onNext(HttpRequest<String> userInfoEntityHttpRequest) {
//                        if (userInfoEntityHttpRequest.getErrno().equals(NetConsts.ERROR_CODE_OK)){
//                            SPUtils.saveLoginToken(userInfoEntityHttpRequest.getData());
//                            HomeActivity.startActivity(BoxAppLication.getBaseApplication());
//                            LUtils.e("登陆成功");
//                        }
//                    }
//                });



    }

    public void getWXUserInfo(Activity activity,String token, String openID,Map<String, String> stringStringMap){

        RequestManager3.getInstance(BoxAppLication.getBaseApplication()).
                getWXUserInfo(token, openID, "zh_CN ")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Observer<WXUserInfoEntity>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull WXUserInfoEntity wxEntity) {
                        if (!TextUtils.isEmpty(wxEntity.getUnionid())&&!TextUtils.isEmpty(wxEntity.getOpenid())&&!TextUtils.isEmpty(wxEntity.getNickname())){

                            stringStringMap.put("openId", wxEntity.getOpenid());
                            com.xls.box2023.utils.SPUtils.saveOpenId(wxEntity.getOpenid());
                            LUtils.e("open=="+wxEntity.getOpenid());
                            stringStringMap.put("unionId", wxEntity.getUnionid());
                            com.xls.box2023.utils.SPUtils.saveunId(wxEntity.getUnionid());
                            stringStringMap.put("nickname", wxEntity.getNickname());
                            stringStringMap.put("headImageUrl", wxEntity.getHeadimgurl());
                            stringStringMap.put("appName", AppUtils.getPackageName(activity));
                            stringStringMap.put("source","box_login");
                            RiskManager.getInstance().reportRisk(RiskManager.login);
                            login(activity,stringStringMap);
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (LoginActivity.loginActivity!=null){
                            LoginActivity.loginActivity.dissmiss();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void login(Activity activity,Map<String, String> stringStringMap) {
        if (BoxAppLication.getBaseApplication().getAppManager().ifHaveActivity(HomeActivity.class.getName())){
            if (LoginActivity.loginActivity!=null){
                LoginActivity.loginActivity.dissmiss();
            }
            return;
        }
        RetrofitBase.getInstace(BoxAppLication.getBaseApplication()).setSubscribe(BoxAppLication.getBaseApplication(), RequestManager.getInstance(BoxAppLication.getBaseApplication()).
                getLogin(stringStringMap), new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {
                SPUtils.saveLoginToken(requestData);
                TUtils.showShort(activity,"登陆成功");
//                BoxAppLication.getBaseApplication().getAppManager().finishAllActivity();
                HomeActivity.startActivity(activity);
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                TUtils.showShort(activity,"登陆失败"+errmsg);
                if (LoginActivity.loginActivity!=null){
                    LoginActivity.loginActivity.dissmiss();
                }
            }
        });
    }


    public void userReg(Activity activity,String unionId,RequestCallBack<String> callBack){
        String channel= ChannelUtils.getChannel(activity);
        LUtils.v("channel---","channel---"+channel);
        LUtils.v("unionId---","unionId---"+unionId);
        if (TextUtils.isEmpty(channel)||TextUtils.equals(channel,"null")||TextUtils.equals(channel,unionId)) {
            callBack.onRequestfail("","");
            return;
        };
        JSONObject data=new JSONObject();
        try {
            data.put("unionId",unionId);
            data.put("parentUnionId",channel);
            RetrofitBase.getInstace(BoxAppLication.getBaseApplication()).setSubscribe(BoxAppLication.getBaseApplication(), RequestManager.getInstance(BoxAppLication.getBaseApplication()).
                    userReg(data.toString()), new RequestCallBack<String>() {
                @Override
                public void onStart() {

                }

                @Override
                public void onStop() {

                }

                @Override
                public void onRequestSuccess(String requestData) {
                    SPUtils.savechannel(activity,channel);
                    callBack.onRequestSuccess(requestData);
                }

                @Override
                public void onRequestfail(String errno, String errmsg) {
                    callBack.onRequestfail(errno,errmsg);
                }
            });
        } catch (JSONException e) {
            callBack.onRequestfail("","");
            throw new RuntimeException(e);
        }
    }


    public void getLoginParams(Activity activity, CallbackT<Map<String, String>> callback) {
        // rxjava contactArray 合并 同步和异步的事件后，最终调用接口
        // 必须有序拼接，才能明确，拼接完成的事件
        Observable<Map<String, String>> observableSystem = Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
            @Override
            public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<Map<String, String>> emitter) throws Throwable {
                Map<String, String> params = new HashMap<>();
                params.putAll(SysDataUtil.getInstance().getLoginInfo(activity));
                emitter.onNext(params);
                //    必须通知
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io());

        Observable<Map<String, String>> observablePicture = Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
            @Override
            public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<Map<String, String>> emitter) throws Throwable {
                SysDataUtil.getInstance().getPictureSum(activity, new CallbackInt() {
                    @Override
                    public void callback(int num) {
                        Map<String, String> params = new HashMap<>();
                        params.put("photos", num + "");
                        emitter.onNext(params);
                        //    必须通知
                        emitter.onComplete();
                    }
                });
            }
        }).subscribeOn(Schedulers.io());

        // 组合参数
        Map<String, String> params = new HashMap<>();
        // merge 是无序的
        Observable.concat(observableSystem, observablePicture)
                .compose(Transformer.transform())
//                .doOnNext()
//                .doOnComplete()
                .subscribe(new Observer<Map<String, String>>() {
                    // subscribe 结束流的标志，没有后续的操作了
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull Map<String, String> map) {
                        params.putAll(map);
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        // concat 事件 完成 后调用 也就是异步获取参数拼接完成后执行
                        if (callback != null) callback.callback(params);
                    }
                });

        // flatMap + doOnNext后， 还可以拼接 其他类型Observavle
        // 这里可以直接加上调用接口的Observavle,形成链式调用,hook不符合rxjva的精髓


    }
    public void getLoginParams2(Activity activity, CallbackT<Map<String, String>> callback) {
        // rxjava contactArray 合并 同步和异步的事件后，最终调用接口
        // 必须有序拼接，才能明确，拼接完成的事件
        Observable<Map<String, String>> observableSystem = Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
            @Override
            public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<Map<String, String>> emitter) throws Throwable {
                Map<String, String> params = new HashMap<>();
                params.putAll(SysDataUtil.getInstance().getLoginInfo2(activity));
                emitter.onNext(params);
                //    必须通知
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io());

        Observable<Map<String, String>> observablePicture = Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
            @Override
            public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<Map<String, String>> emitter) throws Throwable {
                SysDataUtil.getInstance().getPictureSum(activity, new CallbackInt() {
                    @Override
                    public void callback(int num) {
                        Map<String, String> params = new HashMap<>();
                        params.put("photos", num + "");
                        emitter.onNext(params);
                        //    必须通知
                        emitter.onComplete();
                    }
                });
            }
        }).subscribeOn(Schedulers.io());

        // 组合参数
        Map<String, String> params = new HashMap<>();
        // merge 是无序的
        Observable.concat(observableSystem, observablePicture)
                .compose(Transformer.transform())
//                .doOnNext()
//                .doOnComplete()
                .subscribe(new Observer<Map<String, String>>() {
                    // subscribe 结束流的标志，没有后续的操作了
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull Map<String, String> map) {
                        params.putAll(map);
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        // concat 事件 完成 后调用 也就是异步获取参数拼接完成后执行
                        if (callback != null) callback.callback(params);
                    }
                });

        // flatMap + doOnNext后， 还可以拼接 其他类型Observavle
        // 这里可以直接加上调用接口的Observavle,形成链式调用,hook不符合rxjva的精髓


    }

    public void fkCheck(Activity activity,String source, Map<String, String> stringStringMap, RequestCallBack<String> stringRequestCallBack) {

        Map<String, String> data= new LinkedHashMap<>();
        stringStringMap.put("source",source);
        data.put("mdKey",AESUtil.httpRequestProcess(stringStringMap,source));
        data.put("apps",SysDataUtil.getInstance().getPkgList());
        RetrofitBase.getInstace(BoxAppLication.getBaseApplication()).setSubscribe(BoxAppLication.getBaseApplication(), RequestManager.getInstance(BoxAppLication.getBaseApplication()).
                fkCheck(data), new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {
            stringRequestCallBack.onRequestSuccess(requestData);
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                if (errno.equals("2")){
                    TUtils.showShort(activity,"手机太累了，该休息休息了");
                }else if (errno.equals("3")){
                    TUtils.showShort(activity,errmsg);
                    LoginUtil.getInstance().outLogin(activity);
                }else {
                    TUtils.showShort(activity,errmsg);
                }
            }
        });
    }

    public void getAppShareButtion(Activity activity, RequestCallBack<String> stringRequestCallBack) {

        RetrofitBase.getInstace(BoxAppLication.getBaseApplication()).setSubscribe(BoxAppLication.getBaseApplication(), RequestManager.getInstance(BoxAppLication.getBaseApplication()).
                getAppShareButtion(), new RequestCallBack<UserEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(UserEntity requestData) {
                if (requestData.getIsShow()==0){
                    stringRequestCallBack.onRequestSuccess("0");
                }else {
                    stringRequestCallBack.onRequestfail("","");
                }

            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                stringRequestCallBack.onRequestfail(errno,errmsg);
            }
        });
    }
}
